package com.atguigu.gulimall.ware.config;

import com.atguigu.common.exception.BizCodeEnume;
import com.atguigu.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;


@RestControllerAdvice
@Slf4j
public class ExceptionAdvice {

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handlerValidException(MethodArgumentNotValidException e){
        log.error("数据校验出现了问题, 内容为：{},报错类型为：{}",e.getMessage(),e.getClass());
        BindingResult bindingResult = e.getBindingResult();
        Map<String,String> map = new HashMap<>();
        bindingResult.getFieldErrors().forEach((error)->{
            map.put(error.getField(),error.getDefaultMessage());
        });
        return R.error(BizCodeEnume.VAILD_EXCEPTION.getCode(),BizCodeEnume.VAILD_EXCEPTION.getMsg()).put("message",map);
    }

    @ExceptionHandler(value = RuntimeException.class)
    public R runtimeThrowable(RuntimeException e){
        log.error("仓储错误, 内容为：{}",e);
        return R.error(BizCodeEnume.PURCHASE_EXCEPtiON.getCode(),BizCodeEnume.PURCHASE_EXCEPtiON.getMsg());
    }

    @ExceptionHandler(value = Throwable.class)
    public R handlerThrowable(Throwable e){
        log.error("系统未知异常, 内容为：{}",e);
        return R.error(BizCodeEnume.UNKNOW_EXCEPTION.getCode(),BizCodeEnume.UNKNOW_EXCEPTION.getMsg());
    }
}
